package com.wing.productionPlan.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.CodeUtil;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.request.ProductDetailForm;
import com.wing.enterprise.product.model.response.ProductDetailVO;
import com.wing.productionPlan.dao.DynamicDao;
import com.wing.productionPlan.dao.SimpleWorkOrderDao;
import com.wing.productionPlan.model.entity.*;
import com.wing.productionPlan.model.request.ProductionProcessMaterialForm;
import com.wing.productionPlan.model.request.SimpleWorkOrderForm;
import com.wing.productionPlan.model.request.SimpleWorkOrderProcessForm;
import com.wing.productionPlan.model.response.*;
import com.wing.web.excel.WorkOrderExcelIn;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 简版工单表-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class SimpleWorkOrderServiceImpl extends ServiceImpl<SimpleWorkOrderDao, SimpleWorkOrder> implements SimpleWorkOrderService {
    @Autowired
    private SimpleWorkOrderProcessService simpleWorkOrderProcessService;
    @Autowired
    private SimpleWorkOrderDeviceService simpleWorkOrderDeviceService;
    @Autowired
    private DynamicDao dynamicDao;
    @Autowired
    private ProductionProcessMaterialService productionProcessMaterialService;
    @Autowired
    private SimpleWorkOrderProductService simpleWorkOrderProductService;
    @Autowired
    private EnterpriseClient enterpriseClient;
    @Autowired
    private EnterpricceIdService enterpricceIdService;
    @Override
    public int add(SimpleWorkOrderForm simpleWorkOrderForm) {

        //校验

        SimpleWorkOrder simpleWorkOrder =new SimpleWorkOrder();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(SimpleWorkOrder.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(simpleWorkOrderForm, simpleWorkOrder, copyOptions);

        return baseMapper.insert(simpleWorkOrder);
    }

    @Override
    public List<SimpleWorkOrderVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<SimpleWorkOrderVO> pageList4app(Page page, Map<String, Object> params) {
        List<SimpleWorkOrderVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public SimpleWorkOrderVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Transactional
    @Override
    public void submitWorkOrder(SimpleWorkOrderForm simpleWorkOrderForm) {
        LambdaQueryWrapper<SimpleWorkOrder> orderQueryWrapper = new LambdaQueryWrapper();
        orderQueryWrapper.eq(SimpleWorkOrder ::getCode,simpleWorkOrderForm.getCode());
        SimpleWorkOrder simpleWorkOrder = baseMapper.selectOne(orderQueryWrapper);
        //输入的工单编号不存在才添加
        SimpleWorkOrder workOrder = new SimpleWorkOrder();
        if(simpleWorkOrder == null){
            String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
            Integer maxNo = dynamicDao.getMaxNo("ord_simple_work_order");
            String code = CodeUtil.getCode(maxNo);
            workOrder.setEnterpriseCode(JwtUtils.getEnterpriseCode())
                    .setNo(Integer.valueOf(code))
                    .setWorkPlanCode("GD" + today +  code)
                    .setDay(Integer.valueOf(today))
                    .setCreatorName(JwtUtils.getLoginUsername())
                    .setCode(simpleWorkOrderForm.getCode())
                    .setSkuCode(simpleWorkOrderForm.getSkuCode())
                    .setCreator(JwtUtils.getLoginUserId());
            baseMapper.insert(workOrder);
        }
        SimpleWorkOrderProcess simpleWorkOrderProcess = null;
        SimpleWorkOrderProcess simpleWorkOrderProcessForm = new SimpleWorkOrderProcess();
        if(simpleWorkOrderForm.getProcessId() != null){
            LambdaQueryWrapper<SimpleWorkOrderProcess> processQueryWrapper = new LambdaQueryWrapper();
            processQueryWrapper.eq(SimpleWorkOrderProcess ::getSimpleOrderId,simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
            processQueryWrapper.eq(SimpleWorkOrderProcess ::getProcessId,simpleWorkOrderForm.getProcessId());
             simpleWorkOrderProcess = simpleWorkOrderProcessService.getOne(processQueryWrapper);
            if(simpleWorkOrderProcess == null){
                simpleWorkOrderProcessForm.setProcessId(simpleWorkOrderForm.getProcessId())
                        .setSimpleOrderId(simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
                simpleWorkOrderProcessService.save(simpleWorkOrderProcessForm);
            }
        }
        if(CollectionUtils.isNotEmpty(simpleWorkOrderForm.getDeviceList())){
            for (SimpleWorkOrderDevice item  : simpleWorkOrderForm.getDeviceList()){
                LambdaQueryWrapper<SimpleWorkOrderDevice> deviceQueryWrapper = new LambdaQueryWrapper();
                deviceQueryWrapper.eq(SimpleWorkOrderDevice :: getSimpleOrderId,simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
                deviceQueryWrapper.eq(SimpleWorkOrderDevice :: getDeviceCode,item.getDeviceCode());
                SimpleWorkOrderDevice orderDevice = simpleWorkOrderDeviceService.getOne(deviceQueryWrapper);
                if(orderDevice == null){
                    SimpleWorkOrderDevice device = new SimpleWorkOrderDevice();
                    device.setSimpleOrderProcessId(simpleWorkOrderProcess == null ? simpleWorkOrderProcessForm.getId() : simpleWorkOrderProcess.getId());
                    device.setSimpleOrderId(simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
                    device.setDeviceCode(item.getDeviceCode());
                    simpleWorkOrderDeviceService.save(device);
                }
            }
        }
        if(CollectionUtils.isNotEmpty(simpleWorkOrderForm.getSkuCodeList())){
            for(String item : simpleWorkOrderForm.getSkuCodeList()){
                LambdaQueryWrapper<SimpleWorkOrderProduct> productQueryWrapper = new LambdaQueryWrapper();
                productQueryWrapper.eq(SimpleWorkOrderProduct :: getWorkOrderId,simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
                productQueryWrapper.eq(SimpleWorkOrderProduct :: getSkuCode,item);
                SimpleWorkOrderProduct workOrderProduct = simpleWorkOrderProductService.getOne(productQueryWrapper);
                if(workOrderProduct == null){
                    SimpleWorkOrderProduct orderProduct = new SimpleWorkOrderProduct();
                    orderProduct.setWorkOrderId(simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
                    orderProduct.setSkuCode(item);
                    simpleWorkOrderProductService.save(orderProduct);
                }
            }
        }


    }
    @Transactional
    @Override
    public void addSimpleWorkOrder(SimpleWorkOrderForm simpleWorkOrderForm) {
        if (simpleWorkOrderForm == null) {
            throw new BusinessException("参数异常");
        }
        LambdaQueryWrapper<SimpleWorkOrder> orderQueryWrapper = new LambdaQueryWrapper();
        orderQueryWrapper.eq(SimpleWorkOrder ::getCode,simpleWorkOrderForm.getCode());
        SimpleWorkOrder simpleWorkOrder = baseMapper.selectOne(orderQueryWrapper);
        //添加工单
        SimpleWorkOrder workOrder = new SimpleWorkOrder();
        if(simpleWorkOrder == null) {
            String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
            Integer maxNo = dynamicDao.getMaxNo("ord_simple_work_order");
            String code = CodeUtil.getCode(maxNo);
            workOrder.setEnterpriseCode(JwtUtils.getEnterpriseCode())
                    .setNo(Integer.valueOf(code))
                    .setDay(Integer.valueOf(today))
                    .setWorkPlanCode("GD" + today + code)
                    .setCode(simpleWorkOrderForm.getCode())
                    .setSkuCode(simpleWorkOrderForm.getSkuCode())
                    .setProcessId(simpleWorkOrderForm.getProcessId())
                    .setProductionQuantity(simpleWorkOrderForm.getProductionQuantity())
                    .setCreatorName(JwtUtils.getLoginUsername())
                    .setRemark(simpleWorkOrderForm.getRemark());
            baseMapper.insert(workOrder);
        }
        //工序
        LambdaQueryWrapper<SimpleWorkOrderProcess> processQueryWrapper = new LambdaQueryWrapper();
        processQueryWrapper.eq(SimpleWorkOrderProcess ::getSimpleOrderId,simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
        processQueryWrapper.eq(SimpleWorkOrderProcess ::getProcessId,simpleWorkOrderForm.getProcessId());
        SimpleWorkOrderProcess simpleWorkOrderProcess = simpleWorkOrderProcessService.getOne(processQueryWrapper);
        SimpleWorkOrderProcess simpleWorkOrderProcessForm = new SimpleWorkOrderProcess();
        if(simpleWorkOrderProcess == null){
            simpleWorkOrderProcessForm.setProcessId(simpleWorkOrderForm.getProcessId())
                    .setSimpleOrderId(simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
            simpleWorkOrderProcessService.save(simpleWorkOrderProcessForm);
        }

        //设备
        if(CollectionUtils.isNotEmpty(simpleWorkOrderForm.getDeviceList())){
            for (SimpleWorkOrderDevice item  : simpleWorkOrderForm.getDeviceList()){
                LambdaQueryWrapper<SimpleWorkOrderDevice> deviceQueryWrapper = new LambdaQueryWrapper();
                deviceQueryWrapper.eq(SimpleWorkOrderDevice :: getSimpleOrderId,simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
                deviceQueryWrapper.eq(SimpleWorkOrderDevice :: getDeviceCode,item.getDeviceCode());
                SimpleWorkOrderDevice orderDevice = simpleWorkOrderDeviceService.getOne(deviceQueryWrapper);
                if(orderDevice == null){
                    SimpleWorkOrderDevice device = new SimpleWorkOrderDevice();
                    device.setSimpleOrderProcessId(simpleWorkOrderProcess == null ? simpleWorkOrderProcessForm.getId() : simpleWorkOrderProcess.getId());
                    device.setSimpleOrderId(simpleWorkOrder == null ? workOrder.getId(): simpleWorkOrder.getId());
                    device.setDeviceCode(item.getDeviceCode());
                    device.setProductionQuantity(item.getProductionQuantity());
                    simpleWorkOrderDeviceService.save(device);
                }
            }
            /*for (SimpleWorkOrderDevice item  : simpleWorkOrderForm.getDeviceList()){
                SimpleWorkOrderDevice device = new SimpleWorkOrderDevice();
                device.setDeviceCode(item.getDeviceCode())
                        .setThirdPartyCode(simpleWorkOrderForm.getCode())
                        .setProductionQuantity(item.getProductionQuantity())
                        .setSimpleOrderId(workOrder.getId());
                simpleWorkOrderDeviceService.save(device);
            }*/
        }
        if(CollectionUtils.isNotEmpty(simpleWorkOrderForm.getMaterialList())){
            for(ProductionProcessMaterialForm material : simpleWorkOrderForm.getMaterialList()){
                //排产物料
                ProductionProcessMaterial processMaterial = new ProductionProcessMaterial();
                processMaterial.setEnterpriseCode(JwtUtils.getEnterpriseCode());
                processMaterial.setSkuCode(simpleWorkOrderForm.getSkuCode())
                        .setSimpleWorkOrderId(workOrder.getId())
                        .setProcessId(simpleWorkOrderForm.getProcessId())
                        .setMaterialSkuCode(material.getMaterialSkuCode());
                productionProcessMaterialService.save(processMaterial);

            }
        }
    }

    @Override
    public SimpleWorkOrderVO getSimpleWorkOrderVODetails(Long id) {
        SimpleWorkOrderVO workOrderVO = baseMapper.get4appById(id);
        Map<String, Object> params = new HashMap<>();
        params.put("simpleOrderId",id);
        params.put("isDeleted",0);
        List<SimpleWorkOrderProcessVO> processVOList = simpleWorkOrderProcessService.list4app(params);
        workOrderVO.setProcessVOList(processVOList);
        return workOrderVO;
    }
    @Transactional
    @Override
    public void importExcel(List<WorkOrderExcelIn> list) {

        //查询对象集合中的某字段形成新的集合
        List<String> codeList = list.stream().map(WorkOrderExcelIn::getCode).collect(Collectors.toList());
        Map<String, Long> countMap = codeList.stream().filter(item -> StringUtils.isNotBlank(item)).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<String> flag = countMap.keySet().stream().filter(key -> countMap.get(key) > 1).distinct().collect(Collectors.toList());
        if(flag.size() > 0){
            //System.out.println(flag);
            throw new BusinessException("工单编码"+ flag +"重复！");
        }
        int i = 1;
        for(WorkOrderExcelIn item : list){
            i++;
            if(StringUtils.isBlank(item.getCode())){
                throw new BusinessException(300, "第"+i+"行工单编号未输入数据");
            }
            LambdaQueryWrapper<SimpleWorkOrder> orderQueryWrapper = new LambdaQueryWrapper();
            orderQueryWrapper.eq(SimpleWorkOrder ::getCode,item.getCode());
            SimpleWorkOrder workOrder = baseMapper.selectOne(orderQueryWrapper);
            if(workOrder != null){
                throw new BusinessException("工单编码"+ workOrder.getCode() +"已存在数据库！");
            }
            SimpleWorkOrder simpleWorkOrder = new SimpleWorkOrder();
            String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
            Integer maxNo = dynamicDao.getMaxNo("ord_simple_work_order");
            String code = CodeUtil.getCode(maxNo);
            simpleWorkOrder.setEnterpriseCode(JwtUtils.getEnterpriseCode())
                    .setNo(Integer.valueOf(code))
                    .setDay(Integer.valueOf(today))
                    .setWorkPlanCode("GD" + today + code)
                    .setCode(item.getCode());
            baseMapper.insert(simpleWorkOrder);

        }
    }



    public static void main(String[] args) {
        //取出重复的数据
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("1");
        list.add("2");
        list.add("3");
        Map<String, Long> countMap = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<String> flag = countMap.keySet().stream().filter(key -> countMap.get(key) > 1).distinct().collect(Collectors.toList());
        System.out.println(flag);
    }
    @Override
    public SimpleWorkOrderProcessVO getWorkOrderDeviceAndMaterial(Long processId,Long workOrderId) {
        SimpleWorkOrderProcessVO simpleWorkOrderProcessVO = new SimpleWorkOrderProcessVO();
        Map<String, Object> params = new HashMap<>();
        params.put("simpleOrderProcessId",processId);
        params.put("simpleOrderId",workOrderId);
        params.put("isDeleted",0);
        List<SimpleWorkOrderDeviceVO> simpleWorkOrderDeviceVOS = simpleWorkOrderDeviceService.list4app(params);
        simpleWorkOrderProcessVO.setDeviceList(simpleWorkOrderDeviceVOS);
        Map<String, Object> materialParams = new HashMap<>();
        materialParams.put("processId",processId);
        materialParams.put("simpleWorkOrderId",workOrderId);
        materialParams.put("isDeleted",0);
        List<ProductionProcessMaterialVO> materialVOList = productionProcessMaterialService.list4app(materialParams);
        simpleWorkOrderProcessVO.setMaterialList(materialVOList);
        return simpleWorkOrderProcessVO;
    }

    @Transactional
    @Override
    public void addNewSimpleWorkOrder(SimpleWorkOrderForm simpleWorkOrderForm) {
        if (simpleWorkOrderForm == null) {
            throw new BusinessException("参数异常");
        }
        LambdaQueryWrapper<SimpleWorkOrder> orderQueryWrapper = new LambdaQueryWrapper();
        orderQueryWrapper.eq(SimpleWorkOrder ::getCode,simpleWorkOrderForm.getCode());
        SimpleWorkOrder simpleWorkOrder = baseMapper.selectOne(orderQueryWrapper);
        if(simpleWorkOrder != null){
            throw new BusinessException("此工单已存在，请勿重复添加！");
        }
        //添加工单
        SimpleWorkOrder workOrder = new SimpleWorkOrder();
        String today = DateUtil.format(new Date(), DatePattern.PURE_DATE_PATTERN);
        Integer maxNo = dynamicDao.getMaxNo("ord_simple_work_order");
        String code = CodeUtil.getCode(maxNo);
        EnterpricceIdVO enterpricceIdVO = enterpricceIdService.getEnterpricceIdVO();
        workOrder.setEnterpriseCode(enterpricceIdVO.getEnterpriseCode())
                .setNo(Integer.valueOf(code))
                .setDay(Integer.valueOf(today))
                .setWorkPlanCode("GD" + today + code)
                .setCode(simpleWorkOrderForm.getCode())
                .setSkuCode(simpleWorkOrderForm.getSkuCode())
                .setProcessId(simpleWorkOrderForm.getProcessId())
                .setProductionQuantity(simpleWorkOrderForm.getProductionQuantity())
                .setStatus(simpleWorkOrderForm.getStatus())
                .setRemark(simpleWorkOrderForm.getRemark());
        if(StringUtils.isNotBlank(simpleWorkOrderForm.getCreatorName())){
            workOrder.setCreatorName(simpleWorkOrderForm.getCreatorName());
        }else{
            workOrder.setCreatorName(JwtUtils.getLoginUsername());
        }

        baseMapper.insert(workOrder);

        if(CollectionUtils.isNotEmpty(simpleWorkOrderForm.getProcessFormsList())){
            for (SimpleWorkOrderProcessForm item:simpleWorkOrderForm.getProcessFormsList()){
                SimpleWorkOrderProcess process = new SimpleWorkOrderProcess();
                process.setSimpleOrderId(workOrder.getId())
                        .setProcessId(item.getProcessId());
                simpleWorkOrderProcessService.save(process);
                //设备
                if(CollectionUtils.isNotEmpty(item.getDeviceList())){
                    for (SimpleWorkOrderDevice deviceItem  : item.getDeviceList()){
                            SimpleWorkOrderDevice device = new SimpleWorkOrderDevice();
                            device.setSimpleOrderProcessId(item.getProcessId());
                            device.setSimpleOrderId(workOrder.getId());
                            device.setDeviceCode(deviceItem.getDeviceCode());
                            device.setProductionQuantity(deviceItem.getProductionQuantity());
                            simpleWorkOrderDeviceService.save(device);

                    }
                //排产物料
                if(CollectionUtils.isNotEmpty(item.getMaterialList())){
                    for(ProductionProcessMaterialForm material : item.getMaterialList()){
                        ProductionProcessMaterial processMaterial = new ProductionProcessMaterial();
                        processMaterial.setEnterpriseCode(enterpricceIdVO.getEnterpriseCode());
                        processMaterial.setSkuCode(simpleWorkOrderForm.getSkuCode())
                                .setSimpleWorkOrderId(workOrder.getId())
                                .setProcessId(item.getProcessId())
                                .setQuantity(material.getQuantity())
                                .setMaterialSkuCode(material.getMaterialSkuCode());
                        productionProcessMaterialService.save(processMaterial);

                    }
                }
                }
            }
        }
        JsonResult<ProductDetailVO> detailVOJsonResult = enterpriseClient.getProductDetailBySkuCode(simpleWorkOrderForm.getSkuCode());
        if(null == detailVOJsonResult.getData() || detailVOJsonResult.getData().getSkuCode() == null){
            //插入数据到产品详情表
            ProductDetailForm productDetailForm = new ProductDetailForm();
            productDetailForm.setSkuName(simpleWorkOrderForm.getSkuCode());
            productDetailForm.setSkuCode(simpleWorkOrderForm.getSkuCode());
            JsonResult jsonResult = enterpriseClient.addProductDetail(productDetailForm);
            if(jsonResult.getCode() != 200){
                throw new BusinessException("添加工单，产品插入产品详情表异常！");
            }
        }
    }

    @Override
    public void updateWorkOrder(SimpleWorkOrderForm simpleWorkOrderForm) {
        if (simpleWorkOrderForm == null) {
            throw new BusinessException("参数异常");
        }
        SimpleWorkOrder simpleWorkOrder = baseMapper.selectById(simpleWorkOrderForm.getId());
        if(CollectionUtils.isNotEmpty(simpleWorkOrderForm.getProcessFormsList())){
            for (SimpleWorkOrderProcessForm item:simpleWorkOrderForm.getProcessFormsList()){
                SimpleWorkOrderProcess workOrderProcess = simpleWorkOrderProcessService.getOne(new LambdaQueryWrapper<SimpleWorkOrderProcess>()
                        .eq(SimpleWorkOrderProcess::getSimpleOrderId, simpleWorkOrder.getId())
                        .eq(SimpleWorkOrderProcess::getProcessId, item.getProcessId())
                        .eq(SimpleWorkOrderProcess::getIsDeleted,0));
                SimpleWorkOrderProcess process = new SimpleWorkOrderProcess();
                if(workOrderProcess == null){
                    process.setSimpleOrderId(simpleWorkOrder.getId())
                            .setProcessId(item.getProcessId());
                    simpleWorkOrderProcessService.save(process);
                }
                //设备
                if(CollectionUtils.isNotEmpty(item.getDeviceList())){
                    for (SimpleWorkOrderDevice deviceItem  : item.getDeviceList()){
                        SimpleWorkOrderDevice device = new SimpleWorkOrderDevice();
                        SimpleWorkOrderDevice orderDevice = simpleWorkOrderDeviceService.getOne(new LambdaQueryWrapper<SimpleWorkOrderDevice>()
                                .eq(SimpleWorkOrderDevice::getSimpleOrderId, simpleWorkOrder.getId())
                                .eq(SimpleWorkOrderDevice::getSimpleOrderProcessId, item.getProcessId())
                                .eq(SimpleWorkOrderDevice::getDeviceCode,deviceItem.getDeviceCode())
                                .eq(SimpleWorkOrderDevice::getIsDeleted,0));
                        if(orderDevice == null){
                            device.setSimpleOrderProcessId(item.getProcessId());
                            device.setSimpleOrderId(simpleWorkOrder.getId());
                            device.setDeviceCode(deviceItem.getDeviceCode());
                            device.setProductionQuantity(deviceItem.getProductionQuantity());
                            simpleWorkOrderDeviceService.save(device);
                        }else if(orderDevice!=null && orderDevice.getProductionQuantity()!=deviceItem.getProductionQuantity()){
                            orderDevice.setProductionQuantity(deviceItem.getProductionQuantity());
                            simpleWorkOrderDeviceService.updateById(orderDevice);
                        }
                    }
                //排产物料
                if(CollectionUtils.isNotEmpty(item.getMaterialList())){
                    for(ProductionProcessMaterialForm material : item.getMaterialList()){
                        ProductionProcessMaterial processMaterial = new ProductionProcessMaterial();
                        ProductionProcessMaterial serviceOne = productionProcessMaterialService.getOne(new LambdaQueryWrapper<ProductionProcessMaterial>()
                                .eq(ProductionProcessMaterial::getProcessId, item.getProcessId())
                                .eq(ProductionProcessMaterial::getSimpleWorkOrderId, simpleWorkOrder.getId())
                                .eq(ProductionProcessMaterial::getMaterialSkuCode, material.getMaterialSkuCode())
                                .eq(ProductionProcessMaterial::getIsDeleted,0));
                        if(serviceOne == null){
                            processMaterial.setEnterpriseCode(JwtUtils.getEnterpriseCode());
                            processMaterial.setSkuCode(simpleWorkOrderForm.getSkuCode())
                                    .setSimpleWorkOrderId(simpleWorkOrder.getId())
                                    .setProcessId(item.getProcessId())
                                    .setQuantity(material.getQuantity())
                                    .setMaterialSkuCode(material.getMaterialSkuCode());
                            productionProcessMaterialService.save(processMaterial);
                        }else if(serviceOne != null && serviceOne.getQuantity() != material.getQuantity()){
                            serviceOne.setQuantity(material.getQuantity());
                            productionProcessMaterialService.updateById(serviceOne);
                        }
                    }
                 }
                }
            }
        }
    }

    @Transactional
    @Override
    public void cancellationWorkOrderProcess(Long id) {
        SimpleWorkOrderProcess orderProcess = simpleWorkOrderProcessService.getById(id);
        orderProcess.setIsDeleted(true);
        simpleWorkOrderProcessService.updateById(orderProcess);
        List<SimpleWorkOrderDevice> orderDeviceList = simpleWorkOrderDeviceService.list(new LambdaQueryWrapper<SimpleWorkOrderDevice>()
                .eq(SimpleWorkOrderDevice::getSimpleOrderId, orderProcess.getSimpleOrderId()).eq(SimpleWorkOrderDevice::getSimpleOrderProcessId, orderProcess.getProcessId()));
        for (SimpleWorkOrderDevice item : orderDeviceList){
            item.setIsDeleted(true);
            simpleWorkOrderDeviceService.updateBatchById(orderDeviceList);
        }
        List<ProductionProcessMaterial> materialList = productionProcessMaterialService.list(new LambdaQueryWrapper<ProductionProcessMaterial>()
                .eq(ProductionProcessMaterial::getProcessId, orderProcess.getProcessId()).eq(ProductionProcessMaterial::getSimpleWorkOrderId, orderProcess.getSimpleOrderId()));
        for (ProductionProcessMaterial item : materialList){
            item.setIsDeleted(true);
            productionProcessMaterialService.updateBatchById(materialList);
        }
    }

    @Override
    public void cancellationWorkOrderDevice(Long id) {
        SimpleWorkOrderDevice orderDevice = simpleWorkOrderDeviceService.getById(id);
        orderDevice.setIsDeleted(true);
        simpleWorkOrderDeviceService.updateById(orderDevice);
    }

    @Override
    public void cancellationWorkOrderMaterial(Long id) {
        ProductionProcessMaterial processMaterial = productionProcessMaterialService.getById(id);
        processMaterial.setIsDeleted(true);
        productionProcessMaterialService.updateById(processMaterial);
    }

    @Override
    public JsonResult<List<SimpleWorkOrderProcessVO>> getMaterialForecastData(String skuCode,Integer productionQuantity) {
        LambdaQueryWrapper<SimpleWorkOrder> orderQueryWrapper = new LambdaQueryWrapper();
        orderQueryWrapper.eq(SimpleWorkOrder ::getSkuCode,skuCode)
                         .orderByDesc(true,SimpleWorkOrder::getId)
                         .last("limit 1");
        SimpleWorkOrder workOrder = this.baseMapper.selectOne(orderQueryWrapper);
        if(workOrder == null){
            return JsonResult.fail(500,"暂无历史工单数据");
        }
        //有最新的工单数据进行计算
        //查询历史工单的工序
        Map<String, Object> processParams = new HashMap<>();
        processParams.put("simpleOrderId",workOrder.getId());
        List<SimpleWorkOrderProcessVO> processVOList = simpleWorkOrderProcessService.list4app(processParams);
        List<ProductionProcessMaterialVO> materialVOList = new ArrayList<>();
        for (SimpleWorkOrderProcessVO item : processVOList){
            Map<String, Object> params = new HashMap<>();
            params.put("skuCode",skuCode);
            params.put("simpleWorkOrderId",workOrder.getId());
            params.put("processId",item.getProcessId());
             materialVOList = productionProcessMaterialService.list4app(params);
            for (ProductionProcessMaterialVO materialItem : materialVOList){
                if(materialItem.getQuantity() != null){
                    long quantity = new BigDecimal(materialItem.getQuantity()).divide(new BigDecimal(workOrder.getProductionQuantity()),4,BigDecimal.ROUND_HALF_UP)
                            .multiply(BigDecimal.valueOf(productionQuantity
                            )).setScale( 0, BigDecimal.ROUND_UP ).longValue();
                    System.out.println("---------" + quantity);
                    materialItem.setQuantity((int) quantity);
                }
            }
            item.setMaterialList(materialVOList);
        }


        return JsonResult.success(processVOList);
    }

    @Override
    public JsonResult topData() {
        List list = new ArrayList();
        HashMap hm1 = new HashMap();
        hm1.putAll(baseMapper.topDataOne());
        hm1.putAll(baseMapper.topDataTwo());
        list.add(hm1);
        return JsonResult.success("查询成功",list);
    }

    @Override
    public PageResult<UnstartedMaterialsVO> listUnstartedMaterials(Integer page, Integer limit, Map<String, Object> params) {
        List<UnstartedMaterialsVO> list1 = baseMapper.listUnstartedMaterialsOne(params);
        List <UnstartedMaterialsVO> list = new ArrayList<>();
        if (page==(list1.size()/limit)+1){
            for (int i = (page-1)*limit; i < list1.size(); i++) {
                list.add(list1.get(i));
            }
        }else{
            for (int i = (page-1)*limit; i < limit*page; i++) {
                list.add(list1.get(i));
            }
        }
        return new PageResult<>(list, list1.size());
    }

    @Override
    public List<UnstartedMaterialsVO> exportUnstartedMaterials(Map<String, Object> params) {
        List<UnstartedMaterialsVO> list1 = baseMapper.listUnstartedMaterialsOne(params);
        return list1;
    }

    @Override
    public Page<SimpleWorkOrderVO> listOrder(Page page, Map<String, Object> params) {
        List<SimpleWorkOrderVO> list = baseMapper.listOrder(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public JsonResult cancel(Long id) {
        SimpleWorkOrder simpleWorkOrder = baseMapper.selectById(id);
        if (!simpleWorkOrder.getStatus().equals(SimpleWorkOrder.Status.not)){
            return JsonResult.fail("该工单已开工，不能作废");
        }
        simpleWorkOrder.setStatus(SimpleWorkOrder.Status.cancel);
        if (baseMapper.updateById(simpleWorkOrder)>0){
            return JsonResult.success("作废成功");
        }
        return JsonResult.success("作废失败");
    }

}
